package db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import library.LibraryUtil;
import dom.Book;
import dom.BookReservation;
import dom.StudentAccount;
import util.ConfigurationHelper;

/**
 * Handles exporting data structures from the library system to the appropriate database files
 * @author Alex Perkins
 *
 */
public class LibraryDbExporter {

	private final String fieldSplit = ",";
	private final String sectionSplit = ";";
	private final String reservationSplit = "!";
	private boolean debugMode = Boolean.parseBoolean(ConfigurationHelper.getProperty("debug"));
	private LibraryUtil util = new LibraryUtil();
	
	public LibraryDbExporter(){}
	
	
	/**
	 * Converts an array of books to a string and calls the export string function
	 * @param books
	 */
	public void exportBooks(List<Book> books, String libraryId){
		
		StringBuilder sb = new StringBuilder();
		
		sb.append("##################################\n");
		sb.append("# BOOK DATABASE ##################\n");
		sb.append("##################################\n");
		
		if(books!= null){
			for(Book book : books){
				sb.append(book.getName());
				sb.append(fieldSplit);
				sb.append(book.getAuthor());
				sb.append(fieldSplit);
				sb.append(book.getCopies());
				sb.append("\n");
			}
		}
		try{
			writeStringToFile(sb.toString(), ConfigurationHelper.getProperty("books.db",libraryId));
		}
		catch(FileNotFoundException e){
			print("Couldn't export books. Cause: " + e.getMessage());
		}

	}
	
	/**
	 * Converts the accounts data structure to a string and calls the export string function
	 * @param accounts
	 */
	public void exportAccounts(HashMap<String,List<StudentAccount>> accounts, String libraryId){
		
		StringBuilder sb = new StringBuilder();
		
		sb.append("##################################\n");
		sb.append("# ACCOUNTS ACCOUNTS DATABASE ######\n");
		sb.append("##################################\n");
		
		if(accounts != null){
			for(String key : accounts.keySet()){
				
				List<StudentAccount> studentAccounts = accounts.get(key);
				
				if(studentAccounts.isEmpty()){
					continue;
				}
				
				for(StudentAccount studentAccount : studentAccounts){
					
					sb.append(studentAccount.getFirstName());
					sb.append(fieldSplit);
					sb.append(studentAccount.getLastName());
					sb.append(fieldSplit);
					sb.append(studentAccount.getEmailAddress());
					sb.append(fieldSplit);
					sb.append(studentAccount.getPhoneNumber());
					sb.append(fieldSplit);
					sb.append(studentAccount.getUsername());
					sb.append(fieldSplit);
					sb.append(studentAccount.getPassword());
					sb.append(fieldSplit);
					sb.append(studentAccount.getEdu().toString());
					
					int numResevations = 0;
					if(studentAccount.getBookResevations() != null){
						numResevations = studentAccount.getBookResevations().size();
					}
					
					int count = 1;
					
					if(numResevations > 0){
						sb.append(sectionSplit);
						for(BookReservation bookReservation : studentAccount.getBookResevations()){
							
							if(bookReservation.getBook() == null){
								print("exporting a book reservation with a book that is null");
								continue;
							}
							
							sb.append(bookReservation.getBook().getName());
							sb.append(fieldSplit);
							sb.append(bookReservation.getBook().getAuthor());
							sb.append(fieldSplit);
							sb.append(util.getStringFromDate(bookReservation.getReservationDate()));
							sb.append(fieldSplit);
							sb.append(util.getStringFromDate(bookReservation.getDueDate()));
							
							if(count < numResevations){
								sb.append(reservationSplit);
							}
							count++;
						}
					}
					
					sb.append("\n");
					
				} // for each student account
				
			} // for each key in accounts hash
		}
		try{
			writeStringToFile(sb.toString(), ConfigurationHelper.getProperty("accounts.db",libraryId));
		}
		catch(FileNotFoundException e){
			print("Couldn't export accounts. Cause: " + e.getMessage());
		}
	}
	
	/**
	 * Writes a string to a file
	 * @param value
	 * @param path
	 */
	public void writeStringToFile(String value, String path) throws FileNotFoundException {
	
		//debug("==  writing to "+path+ "===========================================================");
		//debug(value);
		//debug("====================================================================================");
		PrintWriter writer = null;
		try{
			String fullpath = "db" + File.separator + path;
			writer = new PrintWriter(fullpath);
			writer.write(value);
			writer.close();
		}
		catch(FileNotFoundException e){
			print(e.getMessage());
			throw e;
		}
		
	}
	
	/**
	 * Checks if the server is in debug mode before printing to console
	 * @param msg
	 */
	private void debug(String msg){
		if(debugMode){
			print(msg);
		}
	}

	/**
	 * Prints
	 * @param msg
	 */
	private void print(String msg){
		System.out.println(msg);
	}

}
